# Plot 3D graphs of the temperature-performance relationships

library(readxl)
library(plotly)
library(dplyr)
library(tidyr)

# set your own local path where you put the JAERE_Submission folder
PATH = "C:/Users/zhenx/Dropbox/Research/Temperature and Athletes/temp_acclimatization/Code"

WORKPATH = paste0(PATH,"JAERE_Submission/Results/Simulations/Baseline")
setwd(WORKPATH)

######################################################################################

data <- read_excel("Semi_Parametric_Model_Prediction_3D.xlsx",sheet = "Sheet1")

linear_spline_3knot <- spread(data[,c("i","j","y_Linear_Spline_3knots")], i, y_Linear_Spline_3knots)
linear_spline_3knot <- subset(linear_spline_3knot,select = -c(j))

linear_spline_2knot <- spread(data[,c("i","j","y_Linear_Spline_2Knots")], i, y_Linear_Spline_2Knots)
linear_spline_2knot <- subset(linear_spline_2knot,select = -c(j))

cubic_spline <- spread(data[,c("i","j","y_Cubic_Spline")], i, y_Cubic_Spline)
cubic_spline <- subset(cubic_spline,select = -c(j))

quadratic <- spread(data[,c("i","j","y_Quadratic")], i, y_Quadratic)
quadratic <- subset(quadratic,select = -c(j))

cubic <- spread(data[,c("i","j","y_Cubic")], i, y_Cubic)
cubic <- subset(cubic,select = -c(j))

meet_tavg <- seq(30.6,90,by=0.6)
team_tavg <- seq(40,  90,by=0.5)

axx <- list(title = "Competition Temperature")
axy <- list(title = "Training Temperature")
axz <- list(title = "Predicted Performance")

fig_linear_spline_3knot <- plot_ly(x=meet_tavg, y=team_tavg, z = ~as.matrix(linear_spline_3knot))%>%add_surface
fig_linear_spline_3knot <- fig_linear_spline_3knot %>% layout(title = "Linear Spline with 3 Knots",scene = list(xaxis=axx,yaxis=axy,zaxis=axz))
fig_linear_spline_3knot       
        
fig_linear_spline_2knot <- plot_ly(x=meet_tavg, y=team_tavg, z = ~as.matrix(linear_spline_2knot))%>%add_surface
fig_linear_spline_2knot <- fig_linear_spline_2knot %>% layout(title = "Linear Spline with 2 Knots",scene = list(xaxis=axx,yaxis=axy,zaxis=axz))
fig_linear_spline_2knot  

fig_cubic_spline <- plot_ly(x=meet_tavg, y=team_tavg, z = ~as.matrix(cubic_spline))%>%add_surface
fig_cubic_spline <- fig_cubic_spline %>% layout(title = "Cubic Spline",scene = list(xaxis=axx,yaxis=axy,zaxis=axz))
fig_cubic_spline  

fig_cubic <- plot_ly(x=meet_tavg, y=team_tavg, z = ~as.matrix(cubic))%>%add_surface
fig_cubic <- fig_cubic %>% layout(title = "Cubic",scene = list(xaxis=axx,yaxis=axy,zaxis=axz))
fig_cubic  

fig_quadratic <- plot_ly(x=meet_tavg, y=team_tavg, z = ~as.matrix(quadratic))%>%add_surface
fig_quadratic <- fig_quadratic %>% layout(title = "Quadratic",scene = list(xaxis=axx,yaxis=axy,zaxis=axz))
fig_quadratic  
        
        